﻿using HttpApiGateway.Interface;
using HttpApiGateway.Model;
using RpcClient.Interface;
using System;

namespace HttpApiGateway.Config
{
    internal class HttpConfig : IHttpConfig
    {
        private static DefHttpConfig _DefConfig = null;
        private static Action<IHttpConfig, string> _refreshEvent;
        static HttpConfig()
        {
            _DefConfig = RpcClient.RpcClient.Config.GetConfigVal<DefHttpConfig>("gateway:http", new DefHttpConfig());
            RpcClient.RpcClient.Config.AddRefreshEvent(_Refresh);
        }

        private static void _Refresh(IConfigServer config, string name)
        {
            if (name == "gateway:http" || name.StartsWith("gateway:http:"))
            {
                _DefConfig = RpcClient.RpcClient.Config.GetConfigVal<DefHttpConfig>("gateway:http", new DefHttpConfig());
                _refreshEvent?.Invoke(new HttpConfig(), name.Remove(0, 13));
            }
        }

        public bool CheckContentLen(long len)
        {
            return _DefConfig.MaxRequstLength == 0 || len < _DefConfig.MaxRequstLength;
        }

        public void RefreshEvent(Action<IHttpConfig, string> action)
        {
            _refreshEvent += action;
        }

        /// <summary>
        /// Api响应模板
        /// </summary>
        public IApiResponseTemplate ApiTemplate
        {
            get;
            set;
        } = new Response.ApiResponseTemplate();
        /// <summary>
        /// 网关地址
        /// </summary>
        public Uri Url => _DefConfig.Url;

        public string ApiRouteFormat => _DefConfig.ApiRouteFormat;
        /// <summary>
        /// 最大请求长度
        /// </summary>
        public long MaxRequstLength => _DefConfig.MaxRequstLength;

        public UpConfig UpConfig => _DefConfig.UpConfig;
    }
}
